package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.DelegateTaskListAdapter;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.DelegateTaskOriginal;
import com.isunland.managesystem.entity.ExcManContent;
import com.isunland.managesystem.entity.PlanDetail;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.MyUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import org.json.JSONException;

//BaseListFragment基础类,封装了 1. 联网.下拉刷新 2. 错误页面,空页面
public class DelegateTaskListFragment extends BaseListFragment {
  //public static final String EXTRA_ADDDELAGATETASK = "com.isunland.managesystem.entity.extra_adddelagatetask";
  //private static final String TAG = "DelegateTaskListFragment";
  /**
   * 筛选执行人
   */
  private static final int SELECT_EXCMAN = 0;
  /**
   * 添加委派任务
   */
  private static final int ADD_DELEGATETASK = 1;
  /**
   * 委派任务详情
   */
  private static final int DETAIL_DELEGATETASK = 2;
  /**
   * 长按删除委派任务
   */
  private static final int DELETE_DELEGATETASK = 3;
  private DelegateTaskListAdapter mAdapter;
  private BaseVolleyActivity mActivity;
  private ArrayList<PlanDetail> mtasks;// JSON解析后的list集合
  private PlanDetail delegateTaskContent;
  //private DialogFragment mDialog; // 长按显示dialog
  //private FragmentManager mFm;
  private String mJobNo = "";
  private ArrayList<PlanDetail> mtaskList;// 备份JSON解析后的list集合

  @Override public void initView(View view, Bundle savedInstanceState) {
    super.initView(view, savedInstanceState);
    mListview.setDividerHeight(0);
  }

  @Override public String getUrl() {
    return ApiConst.URL_DELEGATETTASK_LIST;// 委派任务url
  }

  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<>();
    params.put("curPage", 1 + "");
    params.put("pageSize", 1000 + "");
    params.put("task_excManIds", mJobNo);
    return params;
  }

  // 解析json--判断解析出来的DelegateTaskOriginal是不是没有内容
  @Override public void resolveResponse(String arg0) {
    // 为空什么都不做
    DelegateTaskOriginal original = new Gson().fromJson(arg0, DelegateTaskOriginal.class);

    // 不为空时，将list显示
    List<PlanDetail> taskRows = original.getDelegateRows();

    // 如果matask为空，就new
    if (mtasks == null) {
      mtasks = new ArrayList<>();
    }
    // mtasks不为空时，先清空，将解析出来的集合taskRows放入到mtask
    mtasks.clear();
    mtasks.addAll(taskRows);
    setAdapter(taskRows);
    if (TextUtils.isEmpty(mJobNo)) {
      // jobNo为空时,获取所有,更新mtask列表.用于本地筛选.
      mtaskList = new ArrayList<>(mtasks);
    }
  }

  private void setAdapter(List<PlanDetail> contacts) {
    if (contacts == null) {
      contacts = new ArrayList<>();
    }
    if (mAdapter == null) {
      // 将mtasks放入适配器显示
      mAdapter = new DelegateTaskListAdapter(getActivity(), contacts);
      setListAdapter(mAdapter);
    } else {
      mAdapter.clear();
      mAdapter.addAll(contacts);
      ((DelegateTaskListAdapter) getListAdapter()).notifyDataSetChanged();
    }
    getListView().setOnItemLongClickListener(new OnItemLongClickListener() {

      @Override
      public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        delegateTaskContent = mtasks.get(arg2 - 1);
        FragmentManager fm = getActivity().getSupportFragmentManager();
        DialogFragment dialog = BaseConfirmDialogFragment.newInstance(R.string.deleteConfirm);
        dialog.setTargetFragment(DelegateTaskListFragment.this, DELETE_DELEGATETASK);
        dialog.show(fm, "");
        return true;
      }
    });
  }

  public void refresh() {
    volleyPost();
  }

  // 点击item跳转到详细委派任务fragment，并将delegateTask传过去
  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    delegateTaskContent = mtasks.get(position - 1);
    Intent i = new Intent(getActivity(), DetailDelegateTaskActivity.class);
    i.putExtra(DetailDelegateTaskFragment.EXTRA_DELAGATETASK, delegateTaskContent);
    startActivityForResult(i, DETAIL_DELEGATETASK);
  }

  // 菜单按钮，标题和返回
  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    setHasOptionsMenu(true);
    ActionBar actionBar = ((BaseVolleyActivity) getActivity()).getSupportActionBar();
    if (actionBar != null) {
      actionBar.setTitle(R.string.delegateTask);
    }
    inflater.inflate(R.menu.menu_delegatetask, menu);
    mActivity = (BaseVolleyActivity) getActivity();
    super.onCreateOptionsMenu(menu, inflater);
  }

  // 点击添加按钮跳转到添加委派任务界面
  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.menu_item_add:
        Intent intent = new Intent(getActivity(), AddDelegateTaskActivity.class);
        startActivityForResult(intent, ADD_DELEGATETASK);
        break;
      // 点击搜索弹出对话框,将执行人工号和姓名list集合传递到dialogfragment中
      case R.id.menu_item_search1:
        if (mtaskList != null && mtaskList.size() != 0) {
          List<ExcManContent> mexcManList = selectExcMan();
          DialogFragment dialog;
          FragmentManager fm = getActivity().getSupportFragmentManager();
          dialog = new DelegateTaskDialogFragment();
          Bundle bundle = new Bundle();
          bundle.putSerializable("mexcManList", (ArrayList<ExcManContent>) mexcManList);
          dialog.setArguments(bundle);// 执行人信息list通过bundle传递
          dialog.setTargetFragment(DelegateTaskListFragment.this, SELECT_EXCMAN);
          dialog.show(fm, "");
        } else {
          Toast.makeText(getActivity(), "记录为空，快去添加！", Toast.LENGTH_SHORT).show();
        }

        break;
      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  // 筛选执行人的id和姓名放到 List<ExcManContent>中
  private List<ExcManContent> selectExcMan() {
    List<ExcManContent> exeManList = new ArrayList<>();
    for (int i = 0; i < mtaskList.size(); i++) {
      exeManList.add(
          new ExcManContent(mtaskList.get(i).getExcManId(), mtaskList.get(i).getExcManName()));
    }
    return new ArrayList<>(new HashSet<>(exeManList));
  }

  // 委派任务后自动刷新界面
  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    switch (requestCode) {
      case SELECT_EXCMAN:
        //String mNames = data.getStringExtra(DelegateTaskDialogFragment.EXTRA_NAME);
        mJobNo = data.getStringExtra(DelegateTaskDialogFragment.EXTRA_ID);
        volleyPost();
        break;
      case ADD_DELEGATETASK:
        mJobNo = "";// 添加完后刷新所有信息列表
        volleyPost();
        break;
      case DETAIL_DELEGATETASK:
        mJobNo = "";// 在详情列表删除完后刷新所有信息列表
        volleyPost();
        break;
      case DELETE_DELEGATETASK:
        if ("临时任务".equals(delegateTaskContent.getPlanStatus())) {
          Toast.makeText(getActivity(), R.string.notDeldelegateTask, Toast.LENGTH_SHORT).show();
          break;
        }

        volleyPostDelete();// 解析删除
        break;
      default:
        break;
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

  // 解析删除
  private void volleyPostDelete() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_TEMPLAN_DELETE);

    HashMap<String, String> params = new HashMap<>();
    params.put("id", delegateTaskContent.getId());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        // 解析响应的字符串
        SuccessMessage workProcess = new Gson().fromJson(arg0, SuccessMessage.class);
        if (null == workProcess || null == workProcess.getResult()) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        String successType = workProcess.getResult();
        if (successType.equals(SuccessMessage.FAILURE)) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        if (successType.equals(SuccessMessage.SUCCESS)) {
          Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
          getActivity().setResult(Activity.RESULT_OK);
          mJobNo = "";// 删除完后刷新所有信息列表
          volleyPost();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }
}
